package com.hgw.imsever.common.utils;

import com.google.common.hash.Funnels;
import com.google.common.hash.Hashing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.nio.charset.Charset;
import java.util.List;

@Component
public class RedisUtil {

    @Autowired
    private JedisPool jedisPool;


    public void hset(String key, String field, String value) {
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.hset(key, field, value);
        } finally {
            jedis.close();
        }

    }

    public void hdel(String key, String... fields) {
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.hdel(key, fields);
        } finally {
            jedis.close();
        }
    }

    public String hget(String key, String field) {
        Jedis jedis = jedisPool.getResource();
        String val;
        try {
            val = jedis.hget(key, field);
        } finally {
            jedis.close();
        }
        return val;
    }

    /**
     *  位图存储
     *
     * @param key
     * @param value
     * @param bit
     * @return
     */
    public Boolean setBit(String key, String value, boolean bit) {
        Jedis jedis = jedisPool.getResource();
        Boolean aBoolean;
        try {
            aBoolean = jedis.setbit(key, hash(value), bit);
        } finally {
            jedis.close();
        }
        return aBoolean;
    }

    public Boolean getBit(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        Boolean aBoolean;
        try {
            aBoolean = jedis.getbit(key, hash(value));
        } finally {
            jedis.close();
        }
        return aBoolean;
    }

    public Object evalScript(String luaScript, List<String> keys, List<String> args) {
        Jedis jedis = jedisPool.getResource();
        Object eval;
        try {
            String scriptLoad = jedis.scriptLoad(luaScript);
            eval = jedis.evalsha(scriptLoad, keys, args);
        } finally {
            jedis.close();
        }
        return eval;
    }

    private long hash(String key) {
        return Math.abs(Hashing.murmur3_128().hashObject(key, Funnels.stringFunnel(Charset.forName("UTF-8"))).asInt());
    }
}
